#!/usr/bin/env python3
import csv
import json
import os
import sys

import requests


class jq_dict:
    def __init__(self, word):
        """
        声明变量，将网络CGI所需要的必须参数放到__init__中
        """
        self.url = r"http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
        self.header = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 "
                          "Safari/537.36 ",
            "Referer": r"http://fanyi.youdao.com",
            "Origin": r"http://fanyi.youdao.com",
            "Cookie": r"DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; OUTFOX_SEARCH_USER_ID=-1434000387@112.96.67.99; "
                      r"JSESSIONID=abcBYaAfoH3DPbIW6vu5w; OUTFOX_SEARCH_USER_ID_NCOO=1693995450.8224003; "
                      r"___rl__test__cookies=1573373123740 "
        }
        self.data = {}
        self.src_word = word
        self.tgt_word = ""

        # 先判断字典文件是否存在再赋值
        if not os.path.exists('dict.csv'):
            os.mknod('dict.csv')
            self.dict_path = r"dict.csv"
        else:
            self.dict_path = r"dict.csv"

    def search_by_net(self):
        self.data = {
            "i": self.src_word,
            "keyfrom": "fanyi.com",
            "doctype": "json",
            "client": "fanyideskweb",
            "smartresult": "dict"
        }
        try:
            response = requests.post(url=self.url, data=self.data, headers=self.header, )
            text_json = json.loads(response.text)
            self.tgt_word = text_json["translateResult"][0][0]["tgt"]
            print("通过网络请求进行翻译：")
            self.print_result()
            self.write_dict()
        except requests.exceptions.ConnectionError:
            print("连接失败，请检查网络设置！")

    def search_by_local(self):
        """
        调用read_dict方法，先在本地字典中查找
        本地没有记录时，调用search_by_net方法通过网络查找
        :return: None
        """
        if self.read_dict():
            print("通过本地CSV字典进行翻译：")
            self.print_result()
        else:
            self.search_by_net()

    def write_dict(self):
        # 将单词和翻译写入字典文件
        with open(self.dict_path, "a+") as dict_file:
            writer = csv.writer(dict_file)
            writer.writerow([self.src_word, self.tgt_word])

    def read_dict(self):
        """
        :return: 本地字典文件存在单词记录时，返回True
        :return:本地字典文件不存在单词记录时，返回False
        """
        with open(self.dict_path, "r") as dict_file:
            reader = csv.reader(dict_file)
            for row in reader:
                # 遍历所有行，查找字典文件是否有单词记录
                if self.src_word in row:
                    # print(self.src_word)
                    index = row.index(self.src_word)
                    self.tgt_word = row[1 - index]
                    return True
            # 本地没有记录时，返回False
            return False

    def print_result(self):
        print(self.src_word, "------->", self.tgt_word)


if __name__ == "__main__":
    word = ""
    if len(sys.argv) > 1:
        word = sys.argv[1]
    else:
        word = input("Please Input the Word You Want to Translate:")

    jq_test = jq_dict(word)
    jq_test.search_by_local()
